package com.ruoyi.app.controller;

import com.ruoyi.app.domain.MemberUser;
import com.ruoyi.app.service.IMemberUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.sms.SmsUtil;
import com.ruoyi.common.vo.MemberUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.RandomUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app-api/register/")
public class ApiRegisterController extends BaseController {

    @Autowired
    private IMemberUserService memberUserService;
    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${spring.superCode}")
    private String superCode;

    @Anonymous
    @PostMapping("/getValidCode")
    @ResponseBody
    public AjaxResult getValidCode(@RequestBody MemberUserVo member) {

        if (StringUtils.isBlank(member.getUsername()) || StringUtils.isBlank(member.getMobileCode())) {
            return error("参数为空");
        }
        String loginName = member.getUsername().trim();
        String imgCode = member.getMobileCode().trim();
//        String sessImgCode = redisUtils.get(ConstantsRedis.CAPTCHA_IMAGE_UID_ + loginName + "_" + bizType);
        String sessImgCode="";
        // 判断图形验证码是否正确
//        if (!imgCode.equals(sessImgCode)) {
//            return error("图形验证码不正确");
//        }

        MemberUser memberUser = memberUserService.checkEmailIsRegister(loginName);
        if (memberUser == null) {
            return error("该邮箱未注册");
        }
        // 生产短信验证码，存redis
        String code = RandomUtil.randomNumbers(4);

        redisUtils.set(loginName + "_register",code);
        logger.info(loginName+"短信验证码:"+code);
        // 发短信
        //smsUtil.sendSms(loginName, code);
        return success();
    }
    /**
     * 注册接口
     *
     * @param member
     * @return
     */
    @Anonymous
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(@RequestBody MemberUserVo member) {

        if (StringUtils.isEmpty(member.getUsername()) || StringUtils.isEmpty(member.getMobileCode())) {
            return error("参数为空");
        }
        // 判断验证码是否正确
        //String sessMobileCode = redisUtils.get(member.getUsername() + "_register");
        String sessMobileCode = redisUtils.get("verify_"+member.getRenum());
        if (!member.getMobileCode().equals(sessMobileCode)) {
            return error("验证码不正确");
        }


        int row = memberUserService.checkLoginNameIsRegister(member.getUsername());
        if (row > 0) {
            return error("该手机号已注册过");
        }
        String recem = member.getRecemCode();

        String recemid = "0";
        if(!superCode.equals(recem)){
            MemberUser memberUser = memberUserService.checkRecemIsExist(recem);
            if(memberUser == null){
                return error("请输入正确的邀请码");
            }
            recemid = memberUser.getId();
        }

        try {
            member.setCreateTime(new Date());
            member.setStatus(0);
            member.setPoint(0L);
            String codes =  RandomUtil.randomNumbers(6);
            member.setCodes(codes);
            member.setRecemMemberId(recemid);
            member.setRegisterIp(IpUtils.getIpAddr());
            member.setPassword(SecurityUtils.encryptPassword(member.getPassword()));
            member.setNickname(member.getMobile());
            member.setAvatar(member.getMobile());

            // 包括等级其他初始化字段
            int rowMember = memberUserService.insertMemberUser(member);
            if (rowMember <= 0) {
                return error("注册失败");
            }
        }catch(Exception ex){
            return error("注册异常");
        }
        //member.setMemberId(IdUtil.fastSimpleUUID());


        // 发送欢迎邮件
//        mailUtil.sendMail();

        return success("注册成功");
    }
}
